﻿/*
    Copyright (c) 2014, iD Commerce + Logistics
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this list of conditions
    and the following disclaimer. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the documentation and/or other
    materials provided with the distribution.
 
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
    OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IdComLog.Reactive
{
    /// <summary>
    /// Manages watching SQL queries for changes.
    /// </summary>
    /// <remarks>
    /// This uses SqlDependency internally, and is designed to manage a minimal number of connections required.
    /// SqlDependency is a bit of a mess to work with when multiple places in-proc are using it, and this makes that much easier
    /// so long as all the people using it are using it through SqlWatcher.
    /// </remarks>
    public static class SqlWatcher
    {
        /// <summary>
        /// Observes changes to the results of a SQL query.
        /// </summary>
        /// <param name="connectionString">The connection string to use when executing the query.</param>
        /// <param name="commandString">The query to execute.</param>
        /// <returns>A hot observable which publishes changes to the results of the given query.</returns>
        public static IObservable<SqlNotificationEventArgs> ObserveChanges(string connectionString, string commandString)
        {
            IObservable<SqlNotificationEventArgs> evt;

            lock (states)
            {
                ConnectionState state;

                if (!states.TryGetValue(connectionString, out state))
                {
                    Console.WriteLine("Creating con");

                    states[connectionString] = state = new ConnectionState
                    {
                        Connection = new SqlConnection(connectionString)
                    };
                }

                if (!state.Commands.TryGetValue(commandString, out evt))
                {
                    Console.WriteLine("Creating cmd");

                    evt = Observable.Using(() => new SqlCommand(commandString, state.Connection), cmd => ObserveCommand(state, cmd))
                        .Finally(() => ReturnCachedObserver(connectionString, commandString))
                        .Publish()
                        .RefCount();

                    state.Commands[commandString] = evt;
                }
            }

            return evt;
        }

        static IObservable<SqlNotificationEventArgs> ObserveCommand(ConnectionState state, SqlCommand cmd)
        {
            if (state.Connection.State == System.Data.ConnectionState.Open)
            {
                // connection is open and good to go.
                return cmd.ObserveChanges();
            }

            // we need to open the connection.

            return Observable.DeferAsync(async ct =>
            {
                if (cmd.Connection.State != System.Data.ConnectionState.Open)
                {
                    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();

                    if (Interlocked.CompareExchange(ref state.OpenTask, tcs.Task, null) == null)
                    {
                        Console.WriteLine("Opening con.");
                        try
                        {
                            if (!SqlDependency.Start(state.Connection.ConnectionString))
                            {
                                throw new Exception("Unable to start SqlDependency: it has already been started elsewhere. This is a limitation in SqlDependency and to continue execution would be unsafe.");
                            }

                            await cmd.Connection.OpenAsync(ct).ConfigureAwait(false);
                            tcs.TrySetResult(0);
                        }
                        catch (Exception ex)
                        {
                            tcs.TrySetException(ex);
                        }
                    }
                    else
                    {
                        await tcs.Task.ConfigureAwait(false);
                    }
                }

                return Observable.Empty<SqlNotificationEventArgs>();
            })
            .Concat(cmd.ObserveChanges());
        }

        static void ReturnCachedObserver(string connectionString, string commandString)
        {
            ConnectionState state;

            lock (states)
            {
                if (!states.TryGetValue(connectionString, out state))
                {
                    throw new Exception("Connection not found while returning cached SqlWatcher.");
                }

                if (!state.Commands.Remove(commandString))
                {
                    throw new Exception("Command not found while returning cached SqlWatcher.");
                }

                Console.WriteLine("Closing cmd.");

                if (state.Commands.Count == 0 && states.Remove(connectionString))
                {
                    Console.WriteLine("Closing con.");
                    state.Dispose();
                    SqlDependency.Stop(connectionString);
                }
            }
        }

        static readonly Dictionary<string, ConnectionState> states = new Dictionary<string, ConnectionState>();

        sealed class ConnectionState : IDisposable
        {
            public SqlConnection Connection;
            public Task OpenTask;
            public Dictionary<string, IObservable<SqlNotificationEventArgs>> Commands = new Dictionary<string, IObservable<SqlNotificationEventArgs>>();

            public void Dispose()
            {

                if (Connection != null)
                {
                    Connection.Dispose();
                    Connection = null;
                    Commands = null;
                    OpenTask = null;
                }
            }
        }
    }
}
